package com.leo.corelib.utils;

import android.util.Log;

/**
 * author: Leo Liao
 * created on: 22/07/2021 16:24
 * description: A log tool to quickly spot error locations.
 */
public class LogUtils {

    private LogUtils() {

    }

    public static void showLog(String tag, String msg) {
        showLog(tag, msg, 2);
    }

    public static void showLog(String msg) {
        showLog("TAG_DEFAULT", msg, 2);
    }

    /**
     * Private method called by other method to show logs.
     *
     * @param tag             log tag
     * @param msg             log msg
     * @param stackTraceIndex stack trace list from the top layer where this method is called to
     *                        the most bottom layer as where triggers the calling. In this case,
     *                        the 0 index of stack trace is this function and the most bottom layer
     *                        is android native system. If we need to find out where is the exact
     *                        logging location we want to display, the trace element of the exact
     *                        index must be decided. For example, if an Activity shows logging msg
     *                        by a direct call to this method, the 0 index will be this method and
     *                        index 1 will be the that activity.If an Activity
     *                        calls this function indirectly by other method, then index 0 is still
     *                        this function, and index 1 will be that method, and index 2 will be
     *                        the Activity which triggers the calling.
     */
    private static synchronized void showLog(String tag, String msg, int stackTraceIndex) {
        Throwable throwable = new Throwable();
        StackTraceElement element = null;
        try {
            StackTraceElement[] elements = throwable.getStackTrace();
            element = elements[stackTraceIndex];
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();
        if (element != null) {
            String className = element.getClassName();
            className = className.substring(className.lastIndexOf('.') + 1);
            sb.append(className)
                    .append("->")
                    .append(element.getMethodName())
                    .append("->line ")
                    .append(element.getLineNumber())
                    .append("->")
                    .append(msg);
        } else {
            sb.append(msg);
        }
        Log.e(tag, sb.toString());
    }


}
